/*
 * @Author: your name
 * @Date: 2020-06-30 17:19:32
 * @LastEditTime: 2021-12-17 16:59:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vite2-vue3-ts-antd/src/permission/index.ts
 */
import router from '../router'
// import store from '@front/data/store'
// progress bar style
import 'nprogress/nprogress.css'
// progress bar
import NProgress from 'nprogress'

import { clearPending } from '@/common/utils/request'

import { getQueryString } from '@/common/utils'
import { loginOutCas } from '@/common/utils/auth'
import store from '../store'
import { Modal } from 'ant-design-vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
const loginPagePath = '/login'

router.beforeEach(async (to) => {
  ;(document as any).title = to.meta.title || '首页'
  clearPending()
  NProgress.start()
  // 不在免登录白名单列表
  if (!whiteList.includes(to.path)) {
    if (getQueryString('token')) {
      store.dispatch('app/setTokenId', getQueryString('token')).then(() => {
        runRouter(to)
      })
    } else {
      if (store.getters['app/isLogin']) {
        runRouter(to)
      } else {
        store.dispatch('app/generateToken').then((hasTokenId) => {
          if (hasTokenId) {
            runRouter(to)
          } else {
            Modal.warn({
              title: '温馨提示！',
              content: '您已登出，请重新登陆',
              okText: '确定',
              onOk() {
                loginOutCas()
                NProgress.done()
              }
            })
          }
        })
      }
    }
  } else {
    return true
  }

  function runRouter(to: any) {
    if (to.path === loginPagePath) {
      return true
    } else {
      return false
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
